package com.lzq.mq.nameserver.store;

import lombok.Getter;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class ServiceInstanceManager {

    /**
     * 存储服务实例
     * brokerIp:port -> serviceInstance
     */
    @Getter
    private final Map<String, ServiceInstance> serviceInstanceMap = new ConcurrentHashMap<>();

    /**
     * 用于接受心跳的时候保留初始注册时间
     */
    public void putIfExist(ServiceInstance serviceInstance) {
        ServiceInstance currentInstance = this.get(serviceInstance.getIp(),serviceInstance.getPort());
        if(currentInstance!=null && currentInstance.getFirstRegistryTime()!=null) {
            currentInstance.setLastHeartBeatTime(serviceInstance.getLastHeartBeatTime());
        } else {
            throw new RuntimeException("之前心跳缓存已经剔除，请重新注册");
        }

    }

    /**
     * 添加服务实例
     * @param serviceInstance 服务实例对象
     */
    public void put(ServiceInstance serviceInstance) {
        serviceInstanceMap.put(serviceInstance.getIp() + ":" + serviceInstance.getPort(), serviceInstance);
    }

    /**
     * 获取服务实例
     * @param brokerIp broker的ip
     * @param brokerPort broker的端口
     * @return 服务实例对象
     */
    public ServiceInstance get(String brokerIp, Integer brokerPort) {
        return serviceInstanceMap.get(brokerIp + ":" + brokerPort);
    }

    /**
     * 删除服务实例
     * @param brokerIp
     * @param brokerPort
     * @return
     */
    public ServiceInstance remove(String brokerIp, Integer brokerPort) {
        return serviceInstanceMap.remove(brokerIp + ":" + brokerPort);
    }
}
